import React, { BaseSyntheticEvent, useState } from "react";
import Header from "./components/header";
import Search from "./components/search";
import Content from "./components/content";
import Footer from "./components/footer";
import { ITodoList } from "./model/todoList";
import { message } from "antd";
import { produce } from "immer";

const TodoList = () => {
  const [value, setValue] = useState<string>("");
  const [data, setData] = useState<Array<ITodoList>>([
    {
      id: 0,
      title: "sleep",
      done: false,
    },
  ]);
  const [messageApi, contextHolder] = message.useMessage();
  const handleInput = (event: BaseSyntheticEvent) => {
    setValue(event.target.value);
  };
  const handleAdd = () => {
    if (!value) {
      // message.error({
      //   duration: 1,
      //   content: "标题不能为空"
      // })
      message.open({
        type: "error",
        duration: 1,
        content: "标题不能为空",
        style: {
          color: "red",
        },
      });
      return;
    }
    // let newData = [...data];
    // newData.push({
    //   id: data.length,
    //   title: value,
    //   done: false,
    // });
    // setData(newData);
    setData(
      produce((draft) => {
        draft.push({ id: data.length, title: value, done: false });
      })
    );
    setValue("");
    messageApi.success("新增成功", 1);
    // message.config({
    //   sty
    // })
  };
  const handleChange = (event: any, item: ITodoList) => {
    // let newData = [...data];
    // newData = newData.map((todo) => {
    //   if (todo.id === item.id) {
    //     todo.done = event.target.checked;
    //   }

    //   return todo;
    // });

    // setData(newData);
    setData(
      produce((draft) => {
        // draft.map((todo) => {
        //   if (todo.id === item.id) {
        //     todo.done = event.target.checked;
        //   }
        //   return todo;
        // });
        draft.find((todo) => todo.id === item.id)!.done = event.target.checked;
      })
    );
  };
  const handleDel = (index: number) => {
    // let newData = [...data];
    // newData.splice(index, 1);
    setData(
      produce((draft) => {
        draft.splice(index, 1);
      })
    );

    messageApi.success("删除成功", 1);
  };
  return (
    <div className=" flex justify-center items-start flex-col ">
      {contextHolder}
      <Header></Header>
      <Search
        value={value}
        setValue={setValue}
        handleInput={handleInput}
        handleAdd={handleAdd}
      ></Search>
      <Content
        data={data}
        handleChange={handleChange}
        handleDel={handleDel}
      ></Content>
      <Footer data={data}></Footer>
    </div>
  );
};

export default TodoList;
